package com.complex.getejb.dao;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Stateless(name = "GetDAOBeanName", mappedName = "GetDAOBeanName")
@Remote(IGetDAOBean.class)
public class GetDAOBean implements IGetDAOBean {

    private static Connection conn = null;
    private Statement myStatement = null;
    private ResultSet mySet = null;

    private TreeNode nodeInstance = null;
    private static List<TreeNode> nodesValues = new ArrayList<TreeNode>();

    @Override
    public List<TreeNode> getNodesList() throws GetDAOBeanException {

        if(nodesValues.size() > 0) {
            nodesValues.clear();
        }

        conn = DBConnectionPoolUsage.getDBConnection();

        try {

            myStatement = conn.createStatement();
            mySet = myStatement.executeQuery("SELECT * FROM nodes");
            while(mySet.next()) {
                nodeInstance = new TreeNode();
                nodeInstance.setNodeID(mySet.getInt(1));
                nodeInstance.setParentID(mySet.getInt(2));
                nodeInstance.setNodeName(mySet.getString(3));
                nodesValues.add(nodeInstance);
            }
            mySet = null;
            for(int i = 0; i < nodesValues.size(); i++) {
                mySet = myStatement.executeQuery("SELECT A_ID,A_Name,A_Value FROM attributes WHERE N_ID=" + nodesValues.get(i).getNodeID());
                while(mySet.next()) {
                    nodesValues.get(i).addAttribute(mySet.getInt(1), mySet.getString(2), mySet.getString(3));
                }
                mySet = null;
            }

        } catch(SQLException e) {
            new GetDAOBeanException("SQLException! GetDAOBean.getNodesTable() Can't create statement or set", e);
        } finally {
            myStatement = null;
            mySet = null;
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    new GetDAOBeanException("SQLException! GetDAOBean.getNodesTable() Closing connection failed!", e);
                }
            }
        }

        return nodesValues;
    }
}
